import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { addCartAPI, getCartAPI, delCartAPI } from '@/apis/cart.js'
import { useUserStore } from '@/stores/userStore'

export const useCartStore = defineStore('cartStore', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  const cartList = ref([])
  // 获取最新购物车列表
  const updateCartList = async () => {
    const res = await getCartAPI()
    cartList.value = res.result
  }
  // 加入购物车
  const addCartList = async (goods) => {
    if (isLogin.value) {
      // 登陆后，调用接口加入购物车
      await addCartAPI({ skuId: goods.skuId, count: goods.count })
      await updateCartList()
    } else {
      // 本地购物车实现逻辑
      // goods的skuId在cartList里面有没有
      // 有就count+1
      // 没有就push
      const item = cartList.value.find(item => item.skuId === goods.skuId)
      if (item) {
        item.count += item.count
      } else {
        cartList.value.push(goods)
      }
    }
  }
  // 删除购物车
  const delCart = async (skuId) => {
    if (isLogin.value) {
      // 登陆后调用接口删除购物车逻辑
      await delCartAPI([skuId])
      await updateCartList()
    } else {
      // 本地删除购物车逻辑
      cartList.value = cartList.value.filter((item) => item.skuId !== skuId)
    }
  }
  // 清除购物车
  const clearCart = () => {
    cartList.value = []
    // await updateCartList()
  }
  // 商品总数
  const allCount = computed(() => {
    return cartList.value.reduce((a, c) => a + c.count, 0)
  })
  // 商品总价
  const allPrice = computed(() => {
    return cartList.value.reduce((a, c) => a + c.count * c.price, 0)
  })
  // 单选功能
  const singleCheck = (i, selected) => {
    const item = cartList.value.find(item => item.skuId === i.skuId)
    item.selected = selected
  }
  // 全选
  const isAll = computed(() => {
    return cartList.value.every(item => item.selected)
  })
  // 全选功能
  const allCheck = (selected) => {
    cartList.value.forEach((item) => {
      item.selected = selected
    })
  }
  // 选中商品总数
  const selectedCount = computed(() => {
    // 注意 () => {} 需要显示return，否则是undefined；不加{}，不需要显示return
    return cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count , 0)
  })
  // 选中商品总价
  const selectedPrice = computed(() => {
    return cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0)
  })

  return {
    cartList,
    allCount,
    allPrice,
    isAll,
    selectedCount,
    selectedPrice,
    addCartList,
    delCart,
    clearCart,
    singleCheck,
    allCheck,
    updateCartList
  }
}, {
  persist: true
})
